import sys
sys.path.append("../")

from model.CommonDb import *

class CheckTaskController:
    def __init__(self,args):
        self.args = args
        self.table = "check_tasks"

    def run(self):
        if self.args["func"] == "getColumns":
            return self.getAllColumns(self.args["fields"])
        elif self.args["func"] == "getMap":
            return self.getMap(self.args["fields"])
        elif self.args["func"] == "getData":
            return self.getData(self.args["fields"],self.args["page"],self.args["num"],self.args["orderfield"],self.args["asc"])
        elif self.args["func"] == "getRowData":
            return self.getRowData(self.args["fields"], self.args["id"])
        elif self.args["func"] == "update":
            return self.update(self.args["data"])
        elif self.args["func"] == "add":
            return self.add(self.args["data"])
        elif self.args["func"] == "delete":
            return self.delete(self.args["data"])

    def getAllColumns(self,fields):
        db = CommonDb(self.table)
        rs = db.getAllColumns(fields)
        columns = []
        for row in rs:
            option = {'field': row["field"], 'title': row["comment"], 'sort': 'true', 'fixed': 'left'}
            columns.append(option)
        columns.append({'fixed': 'right', 'title':'操作', 'width':'200', 'align':'center', 'toolbar': '#barDemo'})
        return columns

    def update(self,data):
        db = CommonDb(self.table)
        return db.update(data," id="+str(data["id"]))

    def add(self,data):
        db = CommonDb(self.table)
        return db.add(data,True)

    def delete(self,data):
        db = CommonDb(self.table)
        print(data)
        return db.delete_where(" id="+str(data["id"]))

    def getMap(self,fields):
        db = CommonDb(self.table)
        rs = db.getAllColumns(fields)
        map = {}
        for row in rs:
            map[row["field"]] = {"title":row["comment"],"type":row["type"]}
        return map


    def getData(self,fields,page,num,orderfield,asc):
        db = CommonDb(self.table)
        fieldstr = ""
        for option in fields:
            fieldstr += option + ","
        rs = db.getPageData(fieldstr[0:-1],"1",page,num,orderfield,asc)
        return rs

    def getRowData(self,fields,id):
        columns = self.getMap(fields)
        print(columns)
        db = CommonDb(self.table)
        fieldstr = ""
        for option in fields:
            fieldstr += option + ","
        rs = db.getRowData(fieldstr[0:-1]," id="+id)

        return rs